package mc.support.zmq.service;

import com.google.protobuf.InvalidProtocolBufferException;
import mc.support.proto.Biz;
import mc.support.proto.GeneralReq;
import mc.support.proto.GeneralRsp;
import mc.support.zmq.ProtoHelper;
import mc.support.zmq.route.ZmqConnection;
import mc.support.zmq.route.ZmqServerRouter;

/**
 * Created with IntelliJ IDEA. <br/>
 * Author: Francis Yuen    <br/>
 * Date: 2014-10-29  <br/>
 */
public class ZmqServiceImpl implements ZmqService {

    private static final long DEFAULT_TIMEOUT = 5 * 1000;

    private ZmqServerRouter router;

    public void setRouter( ZmqServerRouter router ) {
        this.router = router;
    }

    @Override
    public boolean ping() {
        if ( router.hasAvailable( Biz.SYS_PING.toString() ) ) {
            return ProtoHelper.sysPing( getConnection( Biz.SYS_PING ) );
        }
        return false;
    }

    @Override
    public void doService( ProtoRequest request, ProtoResponse response ) {
        response.parse( send( request, DEFAULT_TIMEOUT ) );
    }

    @Override
    public void doService( ProtoRequest request, ProtoResponse response, long timeout ) {
        response.parse( send( request, timeout ) );
    }

    private GeneralRsp send( ProtoRequest prw, long timeout ) {
        Biz biz = prw.bizType();
        ZmqConnection conn = getConnection( biz );
        GeneralReq req = prw.toProtoObject();
        byte[] bs = conn.sendAndWaitRsp( req.toByteArray(), timeout );
        try {
            return GeneralRsp.parseFrom( bs );
        } catch ( InvalidProtocolBufferException e ) {
            throw new RuntimeException( "invalid response!" );
        } finally {
            conn.close();
        }
    }

    private ZmqConnection getConnection( Biz biz ) {
        return router.acquireOne( biz.toString() );
    }

}
